package com.gnetek.netty.handler;

import cn.hutool.core.util.StrUtil;
import com.gnetek.netty.interf.NettyController;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Description 客户端处理类
 * @Author Darren Huang
 * @Date 2022-11-08 10:18
 */
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
    private static Logger logger = LoggerFactory.getLogger(EchoClientHandler.class);

    private NettyController nettyCtrl;
    public EchoClientHandler(NettyController nettyCtrl){
        this.nettyCtrl = nettyCtrl;
    }
    /**
     * 在到服务器的连接已经建立之后将被调用
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
//        ctx.writeAndFlush(Unpooled.copiedBuffer(ByteBufUtil.decodeHexDump(EchoTestCmd.CMD0001)));//启动发一次心跳
    }

    /**
     * 当从服务器接收到一个消息时被调用
     * @param ctx
     * @param byteBuf
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf byteBuf) throws Exception {
        String msg= ByteBufUtil.hexDump(byteBuf).toUpperCase();
        logger.info("Client received: {}", msg);
        this.nettyCtrl.showMsg(msg, false);
    }

    /**
     * 在处理过程中引发异常时被调用
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error(cause.getMessage());
        ctx.close();
        this.nettyCtrl.disconnect();
    }
}